import Vue from 'vue/dist/vue.js'
import App from './App.vue'
import router from './router'
import store from './store'
import fetch from './fetch';
import qs from 'qs';

import componentConfig from './vantComponent';
import { Lazyload, Toast, Dialog} from 'vant';

Object.keys(componentConfig).forEach(e => {
	Vue.use(componentConfig[e]);
})

import imgLoading from './assets/imgLoading.png';
import imgError from './assets/imgError.png';
Vue.use(Lazyload, {
	loading: imgLoading,
	error: imgError,
});


import money from './filter/money';
import weight from './filter/weight';
import status from './filter/status';
import sex from './filter/sex';
import { async } from 'q';
import VueClipboard from 'vue-clipboard2'
VueClipboard.config.autoSetContainer = true
Vue.use(VueClipboard)

Vue.filter('money', money);
Vue.filter('weight', weight);
Vue.filter('status', status);
Vue.filter('sex', sex);
Vue.prototype.$toast = Toast;
Vue.prototype.$dialog = Dialog;
Vue.prototype.$http = fetch;

import { CouponCell, CouponList } from 'vant';
Vue.use(CouponCell);
Vue.use(CouponList);


Vue.config.productionTip = false;
function isWechat() {
    var ua = window.navigator.userAgent.toLowerCase();
    //通过正则表达式匹配ua中是否含有MicroMessenger字符串
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }
    return false;
}

let wechat = isWechat();


 

let white = ['/login', '/forget', '/regist', '/index', '/goods/list', '/classify', '/order/payOrder', '/mine', '/kefu']; //白名单， 不需要登录也可以进入的页面

router.beforeEach(async (to, from, next) => {
	if (wechat) {
		let {origin, pathname, hash, search} = location;
		let path = origin + pathname + hash;
		let url = `/api/weixin/wx/front/getCode?wxAppId=1&gotoURL=${path}`;
		if (search) {
			search = qs.parse(search.slice(1));
			if (!search.openId) {
				window.location.href = url;
			} else {
				store.commit('updateUserInfo', {openId: search.openId})
			}
		} else {
			window.location.href = url;
		}
	}
	
	if (white.includes(to.path)) {
		next();
		return;
	} 

	if (to.path.indexOf('/goods/detail/') !== -1) {
		next();
		return;
	}
	let token = store.state.userInfo.token;
	let tokenCache = localStorage.getItem('token');
	//如果没有保存token 但是缓存有token  说明是登录过的  
	//直接获取用户信息就好了
	if (!token && tokenCache) {
		store.state.userInfo.token = tokenCache;
		store.dispatch('getUserInfo', tokenCache).then(() => {
			next();
		})
		return;
	}
	if (!token && !tokenCache && !white.includes(to.path)){
		console.log('没有登录、跳转登录');
		next('/login');
		return;
	}
	//其他的基本都属于拿到了token
	next();
})

new Vue({
	el: '#app',
	router,
	store,
	render: h => h(App)
});